var EVENT_REGISTER=[];

function ERROR_LOGGER(data){
	
};

function RegisterEventHandler(name,handler){
	var found=false;
	$.each(EVENT_REGISTER,function(a,b){
		if(b.name===name){
			found=true;
			return;
		}
	});
	if(!found)
	EVENT_REGISTER.push({"handler":handler,"name":name});
}

function FIRE_EVENT(data){
	if(EVENT_REGISTER){
		$.each(EVENT_REGISTER,function(a,b){
			if('function' === (typeof b.handler)){
				b.handler(data,b.name);
			}
		});
	}
}
var adminPanel = angular.module('MicroCampusApplication',["xeditable","ui.bootstrap","ngAnimate"]);
adminPanel.run(function(editableOptions) {
	  editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
	});

adminPanel.factory('cacheFactory', ['$http','$q',function($http,$q){
	$('#LoadingModal').modal('toggle');
	var urlBase = BASE_URL+'json/cache/';
	var defer = $q.defer();
	defer.promise.then(function () {
	    $('#LoadingModal').modal('toggle');
	});
	
	var factory = {};
	factory.yearList=[];
	//loop each year and add to year list
	for(i=1980;i<=2014;i++){
		factory.yearList.push({"id":i,"value":i});
	}
	
	factory.gradeList=[{"id":1,"value":'Nursery'},{"id":2,"value":'KG'},{"id":3,"value":'LKG'},{"id":4,"value":'1st'},{"id":5,"value":'2nd'},
	                   {"id":6,"value":'3rd'},{"id":7,"value":'4th'},{"id":8,"value":'5th'},{"id":9,"value":'6th'},{"id":10,"value":'7th'},
	                   {"id":11,"value":'8th'},{"id":12,"value":'9th'},{"id":13,"value":'10th'},{"id":14,"value":'11th'},{"id":15,"value":'12th'}];
	
	factory.gradePointList=[{"id":1,"":'A'},{"id":2,"value":'A+'},{"id":3,"value":'B'},{"id":4,"value":'B+'},{"id":5,"value":'C'},{"id":6,"value":'D'},
	                   {"id":7,"value":'FAIL'}];
	
	factory.termList=[{"id":1,"value":'1st'},{"id":2,"value":'2nd'},{"id":3,"value":'3rd'},{"id":4,"value":'4th'}];
	factory.medalsList=[{"id":1,"value":'Gold'},{"id":2,"value":'Silver'},{"id":3,"value":'Bronze'},{"id":4,"value":'Participated'}];
	
	factory.competitionLevelList=[{"id":1,"value":'Inter School'},{"id":2,"value":'Intra School'},{"id":3,"value":'State'},{"id":4,"value":'National'},{"id":5,"value":'International'}];
	
	factory.subjects=[];
	factory.sportsList=[];
	factory.competitiveExamList=[];
	factory.socialBehaviourList=[];
	factory.memoryEvents=[];
	factory.certificationList=[];
	// make sure it is always be of equal size of number of calls to server
	var count=5;
	loadCacheFromURL("SUBJECT");
	loadCacheFromURL("SPORTS");
	loadCacheFromURL("MEMORY_EVENTS");
	loadCacheFromURL("CERTIFICATION");
	loadCacheFromURL("SOCIAL_BEHAVIOUR");
	
	
	factory.getYearList=function(){
		return factory.yearList;
	};
	factory.getGradeList=function(){
		return factory.gradeList;
	};
	factory.getTermList=function(){
		return factory.termList;
	};

	factory.getSubjects=function(){
		return factory.subjects;
    }
	
	factory.getGradePoints=function(){
		return factory.gradePointList;
    }
	
	factory.getSportsList=function(){
		return factory.sportsList;
    }
	
	factory.getMedalsList=function(){
		return factory.medalsList;
    }
	
	factory.getSocialBehaviourList=function(){
		return factory.socialBehaviourList;
	}
	factory.getCompetitiveExamList=function(){
		return factory.competitiveExamList;
	}
	
	factory.getCertificationList=function(){
		return factory.certificationList;
	}
	factory.getCompetitionLevelList=function(){
		return factory.competitionLevelList;
	}
	
	
	function loadCacheFromURL(cacheService){
		$http.get(urlBase+"/"+cacheService+"/0").then(function(result){
			setValues(result.data,cacheService);
			count--;
			if(count==0)
				defer.resolve();
		}, function(errors){
			defer.reject("Error");
			alert("error");
		});
	};
	
	function setValues(result,cacheService){
		if(cacheService=='SUBJECT')
			factory.subjects=result;
		
		if(cacheService=='SPORTS')
			factory.sportsList=result;
		
		if(cacheService=='MEMORY_EVENTS')
			factory.memoryEvents=result;
		
		if(cacheService=='CERTIFICATION')
			factory.certificationList=result;
		
		if(cacheService=='SOCIAL_BEHAVIOUR')
			factory.socialBehaviourList=result;
	}
    return factory;
}]);


//navigate through tabs on student data page.
adminPanel.controller("StudentDataController",['cacheFactory',function($scope,$cacheFactory){
	this.selectedTab=0;
	this.contentUrl="";
	this.setTabAction=function(tab,url){
		this.selectedTab=tab;
		this.contentUrl=url;//the the data below tabbed pane
	};
	this.isTabSelected=function(tab){
		return this.selectedTab===tab;
	}
}]);

adminPanel.controller("LeftMenuController",['cacheFactory','$scope','$http','$rootScope',function($cacheFactory,$scope,$http,$rootScope){
	$scope.searchQuery="";
	$scope.searchResult=[];
	$scope.searchCriteria={};
	$scope.selectedStudentProfile={};
	$scope.searchCriteria={}; //will be used in every other page for saving records.
	$scope.isResultFound=false;
	$scope.searchParamOptions = [{
		   name: 'Registration ID',
		   value: '1'
		}, {
		   name: 'Mobile No.',
		   value: '2'
	},
	 {
		   name: 'First Name',
		   value: '3'
	},
	 {
		   name: 'Last Name',
		   value: '4'
	},
	 {
		   name: 'Email',
		   value: '5'
	},{
		   name: 'User Id',
		   value: '6'
	}];
	$scope.searchParameter=$scope.searchParamOptions[0];
	this.mainContentUrl="";
	var thisObject=this;
	this.setPage=function(url){
		this.mainContentUrl=url;
	};
	
	this.submitSearchForm=function(){
		$scope.searchCriteria.searchQuery=$scope.searchQuery;
		$scope.searchCriteria.searchParameter=$scope.searchParameter.value;
		$scope.searchResult=null;
		$http.post(BASE_URL+"admin/handleRequest/utilServices/STUDENT_SEARCH",{"searchCriteria":$scope.searchCriteria}).success(function(data){
			if(data.status=='SUCCESS'){
				thisObject.setPage(BASE_URL+"view/admin/admin_search_result");
				if(data.result && data.result.length>0){
					$scope.searchResult=data.result;
					$scope.isResultFound=true;
				}
			}else{
				thisObject.setPage(BASE_URL+"view/admin/admin_search_result");
				$scope.isResultFound=false;
				alert(data.status +":"+data.msg);
			}
		}).error(function(){
			ERROR_LOGGER("Server Error");
		});
	}
	
	
	//contract: always have valid entity Id
	this.showStudentInfo=function(entityId){
		$scope.searchCriteria.studentEntityId=entityId;
		$http.post(BASE_URL+"admin/handleRequest/utilServices/GET_STUDENT_INFO",{"searchCriteria":$scope.searchCriteria}).success(function(data){
			if(data.status=='SUCCESS'){
				$scope.selectedStudentProfile=data.result[0];
				thisObject.setPage(BASE_URL+"view/shared/student_data");
			}else{
				alert(data.status +":"+data.msg);
			}
		}).error(function(){
			ERROR_LOGGER("Server Error");
		});
	}
	
}]);

adminPanel.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;
            
            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

adminPanel.service('fileService', ['$http', function ($http) {
    this.uploadFileToUrl = function(file,data, uploadUrl,handler,extraDataTobePassedToHandler){
        var fd = new FormData();
        fd.append('file', file);
        fd.append("attachmentVo", new Blob([JSON.stringify(data)],{ type: "application/json" }));
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(data){
        	handler(data,extraDataTobePassedToHandler);
        })
        .error(function(){
        	handler(data);
        });
    };
    
  //called when user delete the file
    this.deleteFile=function(fileId,recordType,handler,extraDataTobePassedToHandler){
		var url = BASE_URL+'shared/fileHandler/FILE_DELETE';
		var data={"recordId":fileId,"recordType":recordType};
		var fd = new FormData();
        fd.append("attachmentVo", new Blob([JSON.stringify(data)],{ type: "application/json" }));
        $http.post(url, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(data){
        	if(handler)
        		handler(data,extraDataTobePassedToHandler);
        })
        .error(function(){
        	if(handler)
        		handler(data);
        });
	};
	
	//called when user try to download the file.
	this.downloadFile=function(fileId,recordType,handler){
		
	};
}]);

adminPanel.directive('slider', function($timeout) {
	  return {
	    restrict: 'AE',
	    replace: true,
	    scope: {
	      images: '='
	    },
	    link: function(scope, elem, attrs) {},
	    template: '<div class="slider">	<div class="slide" ng-repeat="image in images" ng-show="image.visible">	    <img src='+BASE_URL+'shared/filedownload/{{image.id}}/>	  </div>	  <div class="arrows"></div>	</div>'
	  };
});

adminPanel.controller("PhotoController",['$scope','$rootScope',function($scope,$rootScope){
	$scope.images=[];
	$scope.currentIndex = 0; // Initially the index is at the first image
	$rootScope.initPhotoBox=function(a){
		for(var k in a){
			$scope.images[k]=a[k];
		}
		$scope.makeVisible();
	};
	$scope.next = function() {
		$scope.currentIndex < $scope.images.length - 1 ? $scope.currentIndex++ : $scope.currentIndex = 0;
		$scope.makeVisible();
	};
	 
	$scope.prev = function() {
	  $scope.currentIndex > 0 ? $scope.currentIndex-- : $scope.currentIndex = $scope.images.length - 1;
	  $scope.makeVisible();
	};
	
	$scope.makeVisible=function(){
		$scope.images.forEach(function(image) {
		    image.visible = false; // make every image invisible
		  });
		  $scope.images[$scope.currentIndex].visible = true; // make the current image visible
	}
}]);

adminPanel.controller("FileManagerController",['$scope','$rootScope','fileService',function($scope,$rootScope,fileService){
	$scope.fileVo=[];
	$scope.handler;
	$scope.extraDataTobePassedToHandler=[];
	
	$rootScope.initFileParams=function(obj,mergeObject,handler,extraDataTobePassedToHandler){
		for(var k in mergeObject) obj[k]=mergeObject[k];
		$scope.fileVo=obj;
		$scope.handler=handler;
		$scope.extraDataTobePassedToHandler=extraDataTobePassedToHandler;
	};
	// DV Can you use below or ur own script to filter attachment's file size on client side
	// Option 1 https://gist.github.com/yrezgui/5653591 
	/* Option 2 below
	 * 
	 * app.filter('bytes', function() {
		return function(bytes, precision) {
			if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) return '-';
			if (typeof precision === 'undefined') precision = 1;
			var units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'],
				number = Math.floor(Math.log(bytes) / Math.log(1024));
			return (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision) +  ' ' + units[number];
		}
	});
	*/
	$scope.uploadFile=function(){
		var file = $scope.myFile;
		var uploadUrl = BASE_URL+'shared/fileHandler/FILE_UPLOAD';
		fileService.uploadFileToUrl(file,$scope.fileVo, uploadUrl,$scope.handler,$scope.extraDataTobePassedToHandler);
	}
	
	$rootScope.deleteFile=function(recordType,fileId,handler,extraDataTobePassedToHandler){
		fileService.deleteFile(fileId,recordType,handler,extraDataTobePassedToHandler);
	}
	
	$rootScope.downloadFile=function(recordType,fileId,handler){
		fileService.downloadFile(fileId,recordType,handler);
	}
}]);

adminPanel.controller("RecommendationsController",['$scope','$rootScope','$http',function($scope,$rootScope,$http){
	$scope.recommendationVo={};
	var stRecord={};
	//to be called from client, 
	$rootScope.initRecommendations=function(obj,mergeObject){
		$scope.recommendationVo.searchCriteria=obj;
		stRecord.searchCriteria=obj; //push in student record and page vo both,
		if(mergeObject !=null){
			$scope.recommendationVo.recommendationtitle=mergeObject.recommendationtitle;
			$scope.recommendationVo.recommendationText=mergeObject.recommendationText;
			$scope.recommendationVo.id=mergeObject.id;
		}else{
			$scope.recommendationVo={};
		}
	}
	$scope.addRecommendations=function(){
		stRecord.recommendations=[$scope.recommendationVo];
	    var httpResult=$http.post(BASE_URL+'admin/handleRequest/studentRecord/RECOMMENDATION_SAVE', stRecord);
	    httpResult.success(function(data){
	    		FIRE_EVENT({type:"SAVE_RECOMMENDATION",data:data});
	    		//dismiss recommendation box
	    		$scope.recommendationVo={};
	    		$('#recommendationModule').modal('toggle');
	    });
	}
	
	$scope.deleteRecommendations=function(){
		stRecord.recommendations=[$scope.recommendationVo];
	    var httpResult=$http.post(BASE_URL+'admin/handleRequest/studentRecord/RECOMMENDATION_DELETE', stRecord);
	    if(confirm("Are you sure, you want to delete this?"))
	    httpResult.success(function(data){
	    		FIRE_EVENT({type:"DELETE_RECOMMENDATION",data:data});
	    		//dismiss recommendation box
	    		$scope.recommendationVo={};
	    		$('#recommendationModule').modal('toggle');
	    });
	}
}]);

adminPanel.controller('DatepickerCntrl', function ($scope) {
	  $scope.today = function() {
	    $scope.dt = new Date();
	  };
	  $scope.today();

	  $scope.clear = function () {
	    $scope.dt = null;
	  };

	  // Disable weekend selection
	  $scope.disabled = function(date, mode) {
	    return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) );
	  };

	  $scope.toggleMin = function() {
	    $scope.minDate = $scope.minDate ? null : new Date();
	  };
	  $scope.toggleMin();

	  $scope.open = function($event) {
	    $event.preventDefault();
	    $event.stopPropagation();
	    $scope.opened = true;
	  };

	  $scope.dateOptions = {
	    formatYear: 'yy',
	    startingDay: 1
	  };

	  $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
	  $scope.format = $scope.formats[0];
	});
//
//adminPanel.directive('autocomplete', function ($http, $interpolate, $parse) {
//	return {
//	    restrict: 'E',
//	    replace: true,
//	    template: '<input type="text" />',
//	    require: 'ngModel',
//	    compile: function (elem, attrs) {
//	        var modelAccessor = $parse(attrs.ngModel),
//	            labelExpression = attrs.label;
//	        return function (scope, element, attrs, controller) {
//	            var mappedItems = null;
//	            var allowCustomEntry = attrs.allowCustomEntry || false;
//	            elem.autocomplete({
//	                source: function (request, response) {
//	                    $http({
//	                        url: attrs.url,
//	                        method: 'GET',
//	                        params: { qs: request.term }
//	                    })
//	                    .success(function (data) {
//	                        mappedItems = $.map(data, function (item) {
//	                            var result = {};                                    
//	                            if (typeof item === "string") {
//	                                result.label = item.value;
//	                                result.value = item.id;
//
//	                                return result;
//	                            }
//	                            result.label = $interpolate(labelExpression)(item);
//	                            if (attrs.value) {
//	                                result.value = item[attrs.value];
//	                            }
//	                            else {
//	                                result.value = item;
//	                            }
//	                            return result;
//	                        });
//	                        return response(mappedItems);
//	                    });
//	                },
//	                select: function (event, ui) {
//	                    scope.$apply(function (scope) {
//	                        modelAccessor.assign(scope, ui.item.value);
//	                    });
//	                    elem.val(ui.item.label);
//	                    event.preventDefault();
//	                },
//	                change: function (event, ui) {
//	                    var
//	                        currentValue = elem.val(),
//	                        matchingItem = null;
//	                    if (allowCustomEntry) {
//	                        return;
//	                    }
//	                    for (var i = 0; i < mappedItems.length; i++) {
//	                        if (mappedItems[i].label === currentValue) {
//	                            matchingItem = mappedItems[i].label;
//	                            break;
//	                        }
//	                    }                        
//	                    if (!matchingItem) {
//	                        scope.$apply(function (scope) {
//	                            modelAccessor.assign(scope, null);
//	                        });
//	                    }
//	                }
//	            }
//	            );
//	        }
//	    }
//	}
//	});
